package com.young.caching;

import java.util.Map;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.young.expression.ExpressionEvaluator;
import com.young.expression.SpelExpressionEvaluator;
import com.young.util.JoinPointContextUtil;

public aspect CacheAspect {

	private Cache cache = new Cache(true, true, false);
	private ExpressionEvaluator expressionEvaluator = new SpelExpressionEvaluator();
	
	public pointcut cacheAccess(Cachable cachable)
		:execution(@Cachable * *(..)) && @annotation(cachable);
	
	Object around (Cachable cachable) : cacheAccess(cachable) {
		Map<String, Object> jpContextMap = JoinPointContextUtil.getJoinPointContextMap(thisJoinPoint);
		String key = null;
		try{
			key = cachable.cacheStore() + ":" + expressionEvaluator.evaluator(cachable.keyScript(), jpContextMap);
		} catch (Exception ex) {
			System.out.println("Exception evaluating expression "+ex);
			return proceed(cachable);
		}
		Object cachedValue = null;
		try {
			cachedValue = cache.getFromCache(key);
		} catch (NeedsRefreshException ex) {
			cachedValue = proceed(cachable);
			cache.putInCache(key, cachedValue);
		}
		return cachedValue;
	}
}
